﻿
#region Using

using NetBay.Core.BusinessEntities.ActiveDirectory;
using NetBay.Core.BusinessEntities.ActiveDirectory.Objects;
using NetBay.Core.DataAccess;
using NetBay.Core.Extensions;
using NetBay.Core.Log;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.Common;

#endregion
namespace Rio.Manager.DataAccess
{
    public class DA_ActiveDirectory
    {
        #region Enum

        /// <summary>
        /// List of DB functions to access data
        /// </summary>
        private enum DbFunction
        {
            [DescriptionAttribute("")]
            None,
            [DescriptionAttribute("P_AD_USER_FILEDMAP_Update")]
            UpdateRioAndADCorrespondence,
            [DescriptionAttribute("P_AD_USER_FILEDMAP_Get")]
            GetAllRioAndADCorrespondence,
            [DescriptionAttribute("P_AD_OBJECT_MAP_Get")]
            GetAdMappedObject,
            [DescriptionAttribute("P_AD_OBJECT_MAP_Delete")]
            DeleteAdMappedObject,
            [DescriptionAttribute("P_AD_OBJECT_MAP_USER_Add")]
            AddAdMappingUser,
            [DescriptionAttribute("P_AD_OBJECT_MAP_GROUP_Add")]
            AddAdMappingGroup,
            [DescriptionAttribute("P_AD_NAME_USER_FILEDMAP_Get")]
            GetAdNameMapped,
        }

        #endregion Enum

        #region Interface Settings

        #region Get

        /// <summary>Get Rio and Ad correspondence.</summary>
        /// <returns></returns>
        public static IDataReader GetAllRioADCorrespondence()
        {
            //Log.
            LogManager.Instance().LogDebug("DA_ActiveDirectory.GetAllRioADCorrespondence (No parameters)...");

            try
            {
                //Variable initialization.
                var db = DbHelper.DataBase;
                var dbCommand = db.GetNewCommand(DbFunction.GetAllRioAndADCorrespondence.szGetDescription());

                return db.ExecuteReader(dbCommand);
            }
            catch (Exception ex)
            {
                //Error.
                LogManager.Instance().LogError("DA_ActiveDirectory.GetAllRioADCorrespondence Exception [" + ex.Message + "]");
                return null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="p_lGroupId"></param>
        /// <param name="p_eAdObjectType"></param>
        /// <returns></returns>
        public static IDataReader GetAdMappedObject(long p_lGroupId, AdObjectType p_eAdObjectType)
        {
            try
            {
                LogManager.Instance().LogDebug("GetAllAdMappedObject(p_lGroupId<" + p_lGroupId.ToString() + ">)");
                var db = DbHelper.DataBase;

                var dbCommand = db.GetNewCommand(DbFunction.GetAdMappedObject.szGetDescription());
                db.AddInParameter(dbCommand, "p_lGroupId", DbType.Int32, p_lGroupId);
                db.AddInParameter(dbCommand, "p_iObjectType", DbType.Int32, (int)p_eAdObjectType);

                return db.ExecuteReader(dbCommand);
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError("DA_ActiveDirectory --> GetAllAdMappedObject exception[" + ex.Message + "]");
                return null;
            }
        }

        /// <summary>Get AD Name.</summary>
        /// <returns></returns>
        public static IDataReader GetAdNameMapped()
        {
            //Log.
            LogManager.Instance().LogDebug("DA_ActiveDirectory.GetAdNameMapped (No parameters)...");

            try
            {
                //Variable initialization.
                var db = DbHelper.DataBase;
                var dbCommand = db.GetNewCommand(DbFunction.GetAdNameMapped.szGetDescription());

                return db.ExecuteReader(dbCommand);
            }
            catch (Exception ex)
            {
                //Error.
                LogManager.Instance().LogError("DA_ActiveDirectory.GetAdNameMapped Exception [" + ex.Message + "]");
                return null;
            }
        }

        #endregion Get

        #region Add

        /// <summary>Add a user mapping.</summary>
        /// <param name="p_oAdUserToMap">The user Object to map.</param>
        public static bool AddAdUserMapping(AdUser p_oAdUserToMap)
        {
            //Variable initialization.
            var db = DbHelper.DataBase;
            var dbCommand = db.GetNewCommand(DbFunction.AddAdMappingUser.szGetDescription());
            bool l_bResult = true;
            DbTransaction l_oTransaction = null;

            //Log.
            LogManager.Instance().LogDebug("DA_ActiveDirectory.AddAdUserMapping (p_oAdUserToMap.GuidOfAdObject<" + p_oAdUserToMap.GuidOfAdObject + ">)...");

            using (DbConnection l_oDbConnection = db.CreateConnection())
            {
                try
                {
                    //Connection open and initialize transaction.
                    l_oDbConnection.Open();
                    l_oTransaction = l_oDbConnection.BeginTransaction();

                    //Parameters stored procedure.
                    db.AddInParameter(dbCommand, "p_lGroupId", DbType.Int32, p_oAdUserToMap.MappedGroupIdentifier);
                    db.AddInParameter(dbCommand, "p_sLogin", DbType.String, p_oAdUserToMap.Login);
                    db.AddInParameter(dbCommand, "p_sNom", DbType.String, p_oAdUserToMap.Name);
                    db.AddInParameter(dbCommand, "p_sPrenom", DbType.String, p_oAdUserToMap.FirstName);
                    db.AddInParameter(dbCommand, "p_sEmail", DbType.String, p_oAdUserToMap.Email);
                    db.AddInParameter(dbCommand, "p_sAdGuid", DbType.String, p_oAdUserToMap.GuidOfAdObject.ToString());
                    db.AddInParameter(dbCommand, "p_iObjectType", DbType.Int32, (int)p_oAdUserToMap.TypeOfAdObject);
                    db.AddInParameter(dbCommand, "p_sAdName", DbType.String, p_oAdUserToMap.AdName);

                    //Execute Stored procedure.
                    db.ExecuteNonQuery(dbCommand, l_oTransaction);

                    //Commit the database update.
                    l_oTransaction.Commit();
                }
                catch (Exception ex)
                {
                    //Value error return.
                    l_bResult = false;

                    //Transaction rollback.
                    if (l_oTransaction != null)
                        l_oTransaction.Rollback();

                    //Log error.
                    NetBay.Core.Log.LogManager.Instance().LogError("DA_ActiveDirectory.UpdateRioADCorrespondence Exception [" + ex.Message + "]");
                }
            }

            //Return result.
            return l_bResult;
        }

        /// <summary>Add a group mapping.</summary>
        /// <param name="p_oAdGroupToMapToMap">The group object to map.</param>
        public static bool AddAdGroupMapping(AdGroup p_oAdGroupToMapToMap)
        {
            //Variable initialization.
            var db = DbHelper.DataBase;
            var dbCommand = db.GetNewCommand(DbFunction.AddAdMappingGroup.szGetDescription());
            bool l_bResult = true;
            DbTransaction l_oTransaction = null;

            //Log.
            LogManager.Instance().LogDebug("DA_ActiveDirectory.AddAdGroupMapping (p_oAdGroupToMapToMap.GuidOfAdObject<" + p_oAdGroupToMapToMap.GuidOfAdObject + ">)...");

            using (DbConnection l_oDbConnection = db.CreateConnection())
            {
                try
                {
                    //Connection open and initialize transaction.
                    l_oDbConnection.Open();
                    l_oTransaction = l_oDbConnection.BeginTransaction();

                    //Parameters stored procedure.
                    db.AddInParameter(dbCommand, "p_lGroupId", DbType.Int32, p_oAdGroupToMapToMap.MappedGroupIdentifier);
                    db.AddInParameter(dbCommand, "p_sName", DbType.String, p_oAdGroupToMapToMap.Name);
                    db.AddInParameter(dbCommand, "p_sAdGuid", DbType.String, p_oAdGroupToMapToMap.GuidOfAdObject.ToString());
                    db.AddInParameter(dbCommand, "p_iObjectType", DbType.Int32, (int)p_oAdGroupToMapToMap.TypeOfAdObject);
                    db.AddInParameter(dbCommand, "p_sAdName", DbType.String, p_oAdGroupToMapToMap.AdName);

                    //Execute Stored procedure.
                    db.ExecuteNonQuery(dbCommand, l_oTransaction);

                    //Commit the database update.
                    l_oTransaction.Commit();
                }
                catch (Exception ex)
                {
                    //Value error return.
                    l_bResult = false;

                    //Transaction rollback.
                    if (l_oTransaction != null)
                        l_oTransaction.Rollback();

                    //Log error.
                    NetBay.Core.Log.LogManager.Instance().LogError("DA_ActiveDirectory.UpdateRioADCorrespondence Exception [" + ex.Message + "]");
                }
            }

            //Return result.
            return l_bResult;
        }

        #endregion

        #region Add/Update

        /// <summary>Update Rio and Ad correspondence.</summary>
        /// <param name="p_oNewValueCorrespondence">Correspondence value to update.</param>
        /// <returns></returns>
        public static bool UpdateRioADCorrespondence(ObservableCollection<AdInformationUserRio> p_oNewValueCorrespondence)
        {
            //Variable declaration.
            var db = DbHelper.DataBase;
            bool l_bResult = true;
            DbTransaction l_oTransaction = null;

            //Log.
            NetBay.Core.Log.LogManager.Instance().LogDebug("DA_ActiveDirectory.UpdateRioADCorrespondence (p_oNewValueCorrespondence <" + p_oNewValueCorrespondence.ToString() + "> with " + p_oNewValueCorrespondence.Count + " elements.)...");

            using (DbConnection l_oDbConnection = db.CreateConnection())
            {
                try
                {
                    //Connection open and initialize transaction.
                    l_oDbConnection.Open();
                    l_oTransaction = l_oDbConnection.BeginTransaction();

                    //Update all elements.
                    foreach (AdInformationUserRio l_oNewValueCorrespondenceItem in p_oNewValueCorrespondence)
                    {
                        //Command declaration.
                        var dbCommand = db.GetNewCommand(DbFunction.UpdateRioAndADCorrespondence.szGetDescription(), false);
                        db.AddInParameter(dbCommand, "p_iRioFieldId", DbType.Int32, Convert.ToInt32(l_oNewValueCorrespondenceItem.Type));
                        db.AddInParameter(dbCommand, "p_sAdFieldName", DbType.String, l_oNewValueCorrespondenceItem.Value);
                        db.AddInParameter(dbCommand, "p_sAdName", DbType.String, l_oNewValueCorrespondenceItem.AdName);

                        //Execute Stored procedure.
                        db.ExecuteNonQuery(dbCommand, l_oTransaction);
                    }

                    //Commit the database update.
                    l_oTransaction.Commit();
                }
                catch (Exception ex)
                {
                    //Value error return.
                    l_bResult = false;

                    //Transaction rollback.
                    if (l_oTransaction != null)
                        l_oTransaction.Rollback();

                    //Log error.
                    LogManager.Instance().LogError("DA_ActiveDirectory.UpdateRioADCorrespondence Exception [" + ex.Message + "]");
                }
            }

            //Return result.
            return l_bResult;
        }

        #endregion Add/Update

        #region Delete

        /// <summary>Delete a mapped object.</summary>
        /// <param name="p_oAdObjectToDelete">The mapped Object to delete</param>
        public static bool DeleteAdMappedObject(AdObject p_oAdObjectToDelete)
        {
            //Variable declaration.
            var db = DbHelper.DataBase;
            var dbCommand = db.GetNewCommand(DbFunction.DeleteAdMappedObject.szGetDescription());
            bool l_bResult = true;
            DbTransaction l_oTransaction = null;

            //Log.
            LogManager.Instance().LogDebug("DA_ActiveDirectory.DeleteAdMappedObject (p_oAdObjectToDelete<" + p_oAdObjectToDelete + ">)...");

            using (DbConnection l_oDbConnection = db.CreateConnection())
            {
                try
                {
                    //Connection open and initialize transaction.
                    l_oDbConnection.Open();
                    l_oTransaction = l_oDbConnection.BeginTransaction();

                    //Parameters stored procedure.                    
                    db.AddInParameter(dbCommand, "p_lGroupId", DbType.Int32, p_oAdObjectToDelete.MappedGroupIdentifier);
                    db.AddInParameter(dbCommand, "p_sAdObjectGuid", DbType.String, p_oAdObjectToDelete.GuidOfAdObject.ToString());

                    //Execute Stored procedure.
                    db.ExecuteNonQuery(dbCommand, l_oTransaction);

                    //Commit the database update.
                    l_oTransaction.Commit();
                }
                catch (Exception ex)
                {
                    //Value error return.
                    l_bResult = false;

                    //Transaction rollback.
                    if (l_oTransaction != null)
                        l_oTransaction.Rollback();

                    //Log error.
                    LogManager.Instance().LogError("DA_ActiveDirectory.DeleteAdMappedObject Exception [" + ex.Message + "]");
                }
            }

            //Return result.
            return l_bResult;
        }

        #endregion

        #endregion Interface Settings
    }
}